package zkrt.cc.fishelevatorservice.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.filter.OncePerRequestFilter;
import zkrt.cc.fishelevatorservice.common.Constant;
import zkrt.cc.fishelevatorservice.feign.Result;
import zkrt.cc.fishelevatorservice.feign.SmwClient;
import zkrt.cc.fishelevatorservice.filter.token.TokenContext;
import zkrt.cc.fishelevatorservice.filter.vo.UserRightViewModel;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class RequestHandlerFilter extends OncePerRequestFilter implements InitializingBean {

    private final ObjectMapper objectMapper;

    private final SmwClient smwClient;
    private TokenContext tokenContext;

    private static final String TOKEN_HEAD = "Basic ";
    private static final String OPTIONS = "OPTIONS";

    public RequestHandlerFilter(ObjectMapper objectMapper, SmwClient smwClient,TokenContext tokenContext) {
        this.objectMapper = objectMapper;
        this.smwClient = smwClient;
        this.tokenContext = tokenContext;
    }
    @SuppressWarnings("unchecked")
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 清空用户数据
        UserContextHolder.removeUserInfo();

        String reqUri = request.getRequestURI();
        log.info("SprigSecurity开始鉴权，请求地址：{}，请求类型：{}", reqUri, request.getMethod());
        if (
                reqUri.startsWith("/open")
                        ||  reqUri.startsWith("/iot-service")
                        ||  reqUri.startsWith("/swagger-ui.html")
                        ||  reqUri.startsWith("/doc.html")
                        ||  reqUri.startsWith("/webjars")
                        ||  reqUri.startsWith("/swagger-resources")
                        ||  reqUri.startsWith("/v2/api-docs")
                        ||  reqUri.startsWith("/v3/api-docs")
                        ||  reqUri.startsWith("/")  //开发中不鉴权
        ) {
            filterChain.doFilter(request, response);
            return;
        }

        String accessToken = request.getHeader(Constant.TOKEN_HEADER);
        if ((StrUtil.isBlank(accessToken) && !OPTIONS.equals(request.getMethod()))) {
            getResponse(request, response, reqUri);
        } else {
            if(StrUtil.isEmpty(accessToken)){
                getResponse(request, response, reqUri);
            } else if(accessToken.length() < 10) {
                getResponse(request, response, reqUri);
            } else if(!accessToken.contains(TOKEN_HEAD)) {
                getResponse(request, response, reqUri);
            } else {

                // String tempAccessToken = accessToken.replace(TOKEN_HEAD, "").trim();

                tokenContext.setCurrentToken(accessToken); // 设置 Token 到上下文中
                Result<Map<String, Object>> result = smwClient.getUserInfo();
                tokenContext.setCurrentToken(null);


                // Result<Map<String, Object>> result = smwClient.GetUserTokenData(tempAccessToken);
                if(result.getCode() != 0) {
                    getResponse(request, response, reqUri);
                }
                LinkedHashMap<String, Object> userInfo = (LinkedHashMap)result.getResult();
                String userInfoStr = objectMapper.writeValueAsString(userInfo);

                if(StrUtil.isBlank(userInfoStr)) {
                    getResponse(request, response, reqUri);
                } else {
                    UserRightViewModel userRightViewModel = JSONUtil.toBean(userInfoStr, UserRightViewModel.class);

                    // 查询remark,保存电话
                    // setRemark(userRightViewModel);
                    // 组织机构为旧代码
                    UserContextHolder.setUserInfo(userRightViewModel);

                    filterChain.doFilter(request, response);
                }


                // filterChain.doFilter(request, response);
              /*
                String webtoken =  userRedisTemplate.opsForValue().get(CitmsAppConstant.WEBTOKEN+ tempAccessToken);
                String defaultToken =  userRedisTemplate.opsForValue().get(CitmsAppConstant.DEFAULTTOKEN+tempAccessToken);
                if(StrUtil.isBlank(webtoken) && StrUtil.isBlank(defaultToken)) {
                    getResponse(request, response, reqUri);
                } else {
                    UserModel userModel = JSONUtil.toBean(StrUtil.isBlank(defaultToken) ? webtoken : defaultToken, UserModel.class);
                    String userInfoStr = userRedisTemplate.opsForValue().get(CitmsAppConstant.USERINFO + userModel.getUserGUID());
                    if(StrUtil.isBlank(userInfoStr)) {
                        getResponse(request, response, reqUri);
                    } else {
                        UserRightViewModel userRightViewModel = JSONUtil.toBean(userInfoStr, UserRightViewModel.class);

                        // 查询remark,保存电话
                        setRemark(userRightViewModel);
                        // 组织机构为旧代码
                        UserContextHolder.setUserInfo(userRightViewModel);

                        filterChain.doFilter(request, response);
                    }
                }
                */




            }
        }
    }

    private void getResponse(HttpServletRequest request, HttpServletResponse response, String reqUri){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(200);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("status", 401);
        bodyJson.put("code", 401);
        bodyJson.put("msg", "请求未授权！");
        try {
            PrintWriter printWriter = response.getWriter();
            printWriter.append(objectMapper.writeValueAsString(bodyJson));
            log.warn("请求未授权，请求地址：{}", reqUri);
        } catch (IOException e) {
            log.error("设置鉴权失败信息，Response io异常", e);
        }

    }


}
